package com.njupt.sellsec.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 17:30 2018/7/28
 * @Modified By:
 **/
public class CookieUtil {
    public static void setCookie(HttpServletResponse response,
                                   String name,
                                   String value,
                                   int expire){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(expire);
        cookie.setPath("/");
        response.addCookie(cookie);

    }

    public static Cookie getCookie(HttpServletRequest request,
                                   String name){
        Map<String,Cookie> map = readCookieMap(request);
        if (map.containsKey(name)){
            return map.get(name);
        }else {
            return null;
        }

    }

    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        HashMap<String,Cookie> cookieHashMap = new HashMap<>();
        if (cookies!=null){

            for (Cookie cookie: cookies
                    ) {
                cookieHashMap.put(cookie.getName(),cookie);
            }
        }
        return cookieHashMap;
    }
}
